package com.j2009.springbootproject.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.j2009.springbootproject.entity.User;

import java.util.Calendar;
import java.util.HashMap;

/**
 * ClassName: JWTUtils
 * Description:
 * date: 2021/4/6 15:23
 *
 * @author wuyafeng
 * @version 1.0   softeem.com
 */
public class JWTUtils {
    /**
     * 用户登录成功后生成Jwt
     * 使用Hs256算法  私匙使用用户密码
     *
     * @param ttlMillis jwt过期时间
     * @param user      登录成功的user对象
     * @return
     */
        public static String createJWT(long ttlMillis, User user) {
            HashMap<String,Object> map = new HashMap();

            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.SECOND,120); //令牌过期时间

            //1、创建jwt builder
            JWTCreator.Builder builder = JWT.create();

            //设置payload
            builder.withClaim("username",user.getUsername());
            builder.withClaim("password",user.getPassword());
            builder.withClaim("userid",user.getId());

            //设置令牌过期时间
           String token= builder.withExpiresAt(cal.getTime())
                    .sign(Algorithm.HMAC256("!Q@WS#$"));

            return token;
    }

    /**
     * 验证token合法性
     */
    public static DecodedJWT verify(String token) {
        //先验证签名， 需要根据加密前的前面 验证   再解码
        // 创建验证对象
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("!Q@WS#$")).build();
        DecodedJWT verify = jwtVerifier.verify(token);
        return verify;
    }








}
